<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\Address;
use app\model\BlessingOrder;
use app\model\Goods;
use app\model\LotusLamp;
use app\model\Member;
use app\model\Order;
use app\model\Product;
use app\model\ProductOrder;
use think\facade\Db;
use think\facade\Log;

/**
 *
 * @extends Service<OrderService>
 */
class OrderService extends Service
{
    public function getList($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['templeName']) && $searchQuery['templeName'] != '') {
            $w[] = ['name', '=', $searchQuery['templeName']];
        }
        if (!empty($searchQuery['nick']) && $searchQuery['nick'] != '') {
            $w[] = ['nick', '=', $searchQuery['nick']];
        }
        if (!empty($searchQuery['goods_name']) && $searchQuery['goods_name'] != '') {
            $w[] = ['goods_name', 'like', "%" . $searchQuery['goods_name'] . "%"];
        }
        if (!empty($searchQuery['device_no']) && $searchQuery['device_no'] != '') {
            $w[] = ['device_no', '=', $searchQuery['device_no']];
        }
        if (!empty($searchQuery['order_no']) && $searchQuery['order_no'] != '') {
            $w[] = ['order_no', '=', $searchQuery['order_no']];
        }
        if (!empty($searchQuery['salesman_account']) && $searchQuery['salesman_account'] != '') {
            $w[] = ['salesman_account', '=', $searchQuery['salesman_account']];
        }
        if (!empty($searchQuery['status']) && $searchQuery['status'] != '') {
            $w[] = ['status', '=', $searchQuery['status']];
        }
        if (!empty($searchQuery['type']) && $searchQuery['type'] != '') {
            $w[] = ['type', '=', $searchQuery['type']];
        }
        if (!empty($searchQuery['member_id']) && $searchQuery['member_id'] != '') {
            $w[] = ['member_id', '=', $searchQuery['member_id']];
            $memberInfo = Member::where(['member_id' => $searchQuery['member_id']])->find();
            if ($memberInfo) {
                $memberInfo = $memberInfo->toArray();
            }
        }

        if (!empty($searchQuery['paytimeValues'])) {
            if (!is_array($searchQuery['paytimeValues'])) {
                $timeValues = json_decode($searchQuery['paytimeValues']);
            } else {
                $timeValues = $searchQuery['paytimeValues'];
            }
            $w[] = ['pay_time', 'between', $timeValues];
        }
        if (!empty($searchQuery['timeValues'])) {
            if (!is_array($searchQuery['timeValues'])) {
                $timeValues = json_decode($searchQuery['timeValues']);
            } else {
                $timeValues = $searchQuery['timeValues'];
            }
            $w[] = ['create_time', 'between', $timeValues];
        }
        $order = Order::where($w)->page($page, $limit)->order('order_id desc');
        $list = $order->select();
        if (!empty($list)) {
            $list = $list->toArray();
            $goods_ids = array_column($list, 'goods_id');
            $GoodsList = Goods::where('goods_id', 'in', $goods_ids)->select()->toArray();
            $GoodsList = array_column($GoodsList, null, 'goods_id');
            foreach ($list as &$value) {
                if (!empty($GoodsList[$value['goods_id']]['goods_img'])) {
                    $value['goods_img'] = $GoodsList[$value['goods_id']]['goods_img'];
                } else {
                    $value['goods_img'] = '';
                }
                $value['avatar'] = !empty($memberInfo['avatar']) ? $memberInfo['avatar'] : '';
                $value['nick'] = !empty($memberInfo['nick']) ? $memberInfo['nick'] : '';
                $value['earnings'] = $value['commission'];
            }
        }

        return [
            'total' => $order->count(),
            'list' => $list,
        ];
    }

    public function list($page, $limit, $searchQuery = null)
    {
        $w = [];
        $w[] = ['status', '=', 2];
        if (!empty($searchQuery['status']) && $searchQuery['status'] != '') {
            $w[] = ['status', '=', $searchQuery['status']];
        }
        if (!empty($searchQuery['type']) && $searchQuery['type'] != '') {
            $w[] = ['type', '=', $searchQuery['type']];
        }
        $GoodsList = [];
        $order = Order::where($w)->page($page, $limit)->order('order_id desc');
        $list = $order->select();
        if (!empty($list)) {
            $list = $list->toArray();
            $goods_ids = array_column($list, 'goods_id');
            $member_ids = array_column($list, 'member_id');
            $GoodsList = Goods::where('goods_id', 'in', $goods_ids)->select()->toArray();
            $GoodsList = array_column($GoodsList, null, 'goods_id');
            $memberList = Member::where(['member_id' => $member_ids])->select()->toArray();
            $memberList = array_column($memberList, null, 'member_id');
        }
        foreach ($list as &$value) {
            $value['member_info'] = !empty($memberList[$value['member_id']]) ? $memberList[$value['member_id']] : [];
            $value['daily_income'] = !empty($GoodsList[$value['goods_id']]['daily_income']) ? $GoodsList[$value['goods_id']]['daily_income'] : 0;
        }
        return [
            'list' => $list,
        ];
    }

    public function save($data, $member_id)
    {
        $Goods = Goods::where([
            'goods_id' => $data['goods_id']
        ])->find();
        if (!$Goods) {
            throw new BusinessException('认购商品不存在');
        }
        $orderInfo = Order::where([
            'goods_id' => $data['goods_id'], 'member_id' => $member_id
        ])->find();
        if ($orderInfo) {
//            throw new BusinessException('认购商品已下单，不可重复下单');
        }
        $order_no = 'OD' . time() . rand(1000, 9999) . $member_id;
        $today = date('Y-m-d H:i:s', time());
        $rs = Order::create([
            'create_time' => date('Y-m-d H:i:s', time()),
            'order_no' => $order_no,
            'price' => $Goods['goods_price'],
            'goods_name' => $Goods['goods_name'],
            'start_time' => $today,
            'end_time' => date("Y-m-d", strtotime("+2 year", strtotime($today))),
            'status' => 1,
            'type' => 1,
            'goods_id' => $data['goods_id'],
            'member_id' => $member_id,
        ]);
        return $rs;
    }

    //更新订单为已支付，分销分润入账
    public function update($data, $order_id)
    {

        $orderInfo = Order::where([
            'order_id' => $order_id
        ])->find();
        if (!$orderInfo) {
            throw new BusinessException('认购订单不存在');
        }
        $order = $orderInfo->toArray();
        $Goods = Goods::where([
            'goods_id' => $order['goods_id']
        ])->find();
        if (!$Goods) {
            throw new BusinessException('认购商品不存在');
        }

        Db::startTrans();
        $rs = $orderInfo->save(['status' => 2, 'pay_time' => date('Y-m-d H:i:s', time())]);
        if (!$rs) {
            Db::rollback();
            throw new BusinessException('更新订单失败');
        }
        $memberInfo = Member::where(['member_id' => $orderInfo['member_id']])->find()->toArray();
        $map = $orderInfo->toArray();
        if (!empty($memberInfo['pid'])) {
            $map['primary_income'] = $Goods['primary_income'];
            $rs = IncomeService::invoke()->addIncome($map, $memberInfo, 1);
            if (!$rs) {
                Db::rollback();
                throw new BusinessException('更新一级分销分润入账失败');
            }
            $parentMemberInfo = Member::where(['member_id' => $memberInfo['pid']])->find()->toArray();
            if (!empty($parentMemberInfo['pid'])) {
                $map['secondary_income'] = $Goods['secondary_income'];
                $rs = IncomeService::invoke()->addIncome($map, $parentMemberInfo, 2);
                if (!$rs) {
                    Db::rollback();
                    throw new BusinessException('更新二级分销分润入账失败');
                }
            }
        }
        Db::commit();
        return true;
    }

    public function getDetail($order_id, $member_id)
    {
        $orderInfo = Order::where([
            'order_id' => $order_id
        ])->find();
        if (!$orderInfo) {
            throw new BusinessException('订单不存在');
        }
        $Goods = Goods::where([
            'goods_id' => $orderInfo['goods_id']
        ])->find();
        $member = Member::where([
            'member_id' => $orderInfo['member_id']
        ])->find();
        $orderInfo['earnings'] = $orderInfo['commission'];
        $orderInfo['goods_img'] = $Goods['goods_img'];
        $orderInfo['avatar'] = $member['avatar'];
        return $orderInfo;
    }

    public function info($order_id, $member_id = null)
    {
        $w = ['order_id' => $order_id];
        if ($member_id) {
            $w['member_id'] = $member_id;
        }
        $info = ProductOrder::where($w)->find();
        if (!$info) {
            throw new BusinessException('订单不存在');
        }
        return $info;
    }

    public function getDistribution($page, $limit, $searchQuery = null)
    {
        $memberList = $w = [];
        if (!empty($searchQuery['member_id']) && $searchQuery['member_id'] != '') {
            $memberList = Member::where(['pid' => $searchQuery['member_id']])->select()->toArray();
            $member_ids = array_column($memberList, 'member_id');
            $memberList = array_column($memberList, null, 'member_id');
            if (empty($member_ids)) {
                $member_ids = [-1];
            }
            $w[] = ['member_id', 'in', $member_ids];
        }
        $w[] = ['status', '=', 2];
        $order = Order::where($w)->page($page, $limit);
        $list = $order->select();
        if (!empty($list)) {
            $list = $list->toArray();
            $goods_ids = array_column($list, 'goods_id');
            $GoodsList = Goods::where('goods_id', 'in', $goods_ids)->select()->toArray();
            $GoodsList = array_column($GoodsList, null, 'goods_id');
        }
        foreach ($list as &$value) {
            $value['mobile'] = $memberList[$value['member_id']]['mobile'] ?: '';
            if (!empty($GoodsList[$value['goods_id']]['goods_img'])) {
                $value['goods_img'] = $GoodsList[$value['goods_id']]['goods_img'];
            } else {
                $value['goods_img'] = '';
            }
            $value['earnings'] = $value['commission'];
        }
        return [
            'total' => $order->count(),
            'list' => $list,
        ];
    }

    //个人中心获取分销订单金额
    public function getOrderAmount($member_id, $order_id = 0)
    {
        $w = [];
        $w[] = ['status', '=', 2];
        if (!empty($member_id) && $member_id != '') {
            $memberList = Member::where(['pid' => $member_id])->select()->toArray();
            $member_ids = array_column($memberList, 'member_id');
            if (empty($member_ids)) {
                $member_ids = [-1];
            }
            $w[] = ['member_id', 'in', $member_ids];
        }
        if (!empty($order_id) && $order_id != '') {
            $w[] = ['order_id', '=', $order_id];
        }
        $order_amount = Order::where($w)->sum('price');
        return $order_amount ?: 0.00;
    }

    public function payOrder($order_no, $return_data)
    {
        $info = Order::where(['order_no' => $order_no])->find();
        if (!$info) {
            throw new BusinessException('订单不存在');
        }
        if ($info->status != 1) {
            throw new BusinessException('订单已完成');
        }
        $info = $info->toArray();
        $goodsInfo = Goods::where(['goods_id' => $info['goods_id']])->find();
        if (!$goodsInfo) {
            throw new BusinessException('商品不存在');
        }
        $stock = $goodsInfo->stock - 1;
        $sales_initial = $goodsInfo->sales_initial + 1;
        Db::startTrans();
        try {
            $goodsInfo->save(['stock' => $stock, 'sales_initial' => $sales_initial]);
            $info->save(['status' => 2, 'return_data' => $return_data, 'pay_time' => date('Y-m-d H:i:s', time())]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return true;
    }
}